package com.zyy.study.demo;

/**
 * 遍历二叉树demo
 */
public class TreeDemo {
    /**
     * 前序遍历
     * @param treeNode
     */
    private static void preorderTraversal(TreeNode treeNode) {

        if (treeNode != null) {
            System.out.printf(treeNode+" ");
            preorderTraversal(treeNode.leftNode);
            preorderTraversal(treeNode.rightNode);
        }
    }

    /**
     * 中序遍历
     * @param treeNode
     */
    private static void inorderTraversal(TreeNode treeNode) {

        if (treeNode != null) {
            inorderTraversal(treeNode.leftNode);
            System.out.printf(treeNode+" ");
            inorderTraversal(treeNode.rightNode);
        }
    }

    /**
     * 后序遍历
     * @param treeNode
     */
    private static void postorderTraversal(TreeNode treeNode) {

        if (treeNode != null) {
            postorderTraversal(treeNode.leftNode);
            postorderTraversal(treeNode.rightNode);
            System.out.printf(treeNode+" ");
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.leftNode = new TreeNode(2);
        root.rightNode = new TreeNode(3);
        root.leftNode.leftNode = new TreeNode(4);
        root.leftNode.rightNode = new TreeNode(5);
        System.out.println("前序遍历");
        preorderTraversal(root);
        System.out.println();
        System.out.println("中序遍历");
        inorderTraversal(root);
        System.out.println();
        System.out.println("后序遍历");
        postorderTraversal(root);
    }
}
class TreeNode{
    private int value;
    TreeNode leftNode;
    TreeNode rightNode;

    public TreeNode(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

}
